﻿Imports DTO
Imports System.Linq
Imports System.Math

Public Class DiemMHDAO
    Public Function getScore_DAO(ByVal mahs As Integer, ByVal hk As Integer, ByVal year As Integer)
        Dim listdiem As List(Of DiemMHDTO) = New List(Of DiemMHDTO)

        Dim context As DataproviderDataContext = New DataproviderDataContext()
        Dim list = From diem In context.DiemMHs
                   Join hocky In context.HocKies On diem.MaHK Equals hocky.MaHK
                   Where diem.MaHoSo = mahs And hocky.HocKy = hk And hocky.NamHoc = year
                   Select diem.Diem15p, diem.Diem1tiet, diem.DiemCuoiKy, hocky.HocKy, hocky.NamHoc

        Dim avg As Double = 0
        Dim count As Integer = 0
        Dim temp As Double = 0
        Dim total As Double = 0
        Dim score As Double = 0
        Dim i As Integer = 0
        For Each value In list
            Dim entity As DiemMHDTO = New DiemMHDTO()
            entity.Diem15p = value.Diem15p
            entity.Diem1tiet = value.Diem1tiet
            entity.DiemCuoiKy = value.DiemCuoiKy

            temp = entity.Diem15p + entity.Diem1tiet * 2 + entity.DiemCuoiKy * 3


            If IsDBNull(entity.Diem15p) And IsDBNull(entity.Diem1tiet) And IsDBNull(entity.DiemCuoiKy) Then
                count = 0
            ElseIf IsDBNull(entity.Diem15p) And IsDBNull(entity.Diem1tiet) Then
                count = 3
            ElseIf IsDBNull(entity.Diem15p) Then
                count = 5
            Else
                count = 6
            End If

            score = temp / count
            total = total + score
            i = i + 1
        Next

        If i = 0 Then
            avg = 0
        Else
            avg = Round((total / i), 2)
        End If


        Return avg
    End Function

    Public Sub addScore_DAO(ByVal id As Integer, ByVal hkId As Integer)
        Dim context As DataproviderDataContext = New DataproviderDataContext()
        Dim st = New DiemMH

        st.Diem15p = 0
        st.Diem1tiet = 0
        st.DiemCuoiKy = 0
        st.MaHoSo = id
        st.MaHK = hkId
        st.MaMH = "TD"

        context.DiemMHs.InsertOnSubmit(st)
        context.SubmitChanges()
    End Sub
End Class
